package concurrencybasement_1;

import java.util.ArrayList;
import java.util.concurrent.TimeUnit;

/**
 *  测试线程优先级
 *  → Windows 基本忽视了线程优先级的设定，最后输出可以得到，低优先级的与高优先级的线程之间计数结果没有太大差距
 */
public class Priority {
    private static volatile boolean notStart = true;
    private static volatile boolean notEnd = true;

    public static void main(String[] args) throws InterruptedException {
        ArrayList<Job> jobs = new ArrayList<Job>();
        for (int i = 0; i < 10; i++) {
            int priority = i < 5 ? Thread.MIN_PRIORITY : Thread.MAX_PRIORITY;
            Job job = new Job(priority);
            jobs.add(job);
            Thread thread = new Thread(job, "Thread:" + i);
            thread.setPriority(priority);
            thread.start();
        }

        notStart = false;
        TimeUnit.SECONDS.sleep(3);
        notEnd = false;

        for (Job job : jobs) {
            System.out.println("Job Priority : " + job.priority + ", Count : " + job.jobCount);
        }
    }

    static class Job implements Runnable {
        private int priority;
        private long jobCount;

        public Job(int priority) {
            this.priority = priority;
        }
        @Override
        public void run() {
            while (notStart) {
                Thread.yield();
            }
            while (notEnd) {
                Thread.yield();
                jobCount++;
            }
        }
    }
    /**
     * 当调用 Thread.yield() 时：
     *  当前线程从运行状态转为就绪状态
     *  线程调度器可能会选择其他具有相同或更高优先级的线程执行
     *  如果没有符合条件的线程，当前线程可能会继续执行
     */
}
